package top.oylan.manager.controller.admin;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import top.oylan.manager.entity.Role;
import top.oylan.manager.service.RoleService;
import top.oylan.manager.tools.Pager;
import top.oylan.manager.tools.Result;

import javax.annotation.Resource;

/**
 * @Author abduahad
 * @Description ${description}
 * @Date 2019-02-24
 */
@Controller
@RequestMapping("/admin/role")
public class AdminRoleController {

    @Resource
    RoleService roleService;

    @RequestMapping(value = {"/list","","/"},method = {RequestMethod.GET,RequestMethod.POST})
    public String index(@RequestParam(value = "page",defaultValue = "1")Integer page,
                        @RequestParam(value = "roleName",defaultValue = "",required = false)String roleName,
                        ModelMap modelMap){
        Pager pager = new Pager();
        pager.setCurrentPage(page);
        Role condition = new Role();
        pager.setCondition(condition);
        pager.setList(roleService.selectByPager(pager));
        modelMap.addAttribute("pager",pager);

        return "admin/role/list";
    }

    /**
     * 添加
     * @return
     */
    @RequestMapping("/add")
    public String add(){

        return "admin/role/add";
    }

    /*
     *  编辑
     */
    @RequestMapping(value = "/edit",method = RequestMethod.GET)
    public String edit(@RequestParam(value = "id")Integer id,
                       ModelMap modelMap){
        Role role = roleService.selectById(id);
        modelMap.addAttribute("role",role);
        return "admin/role/edit";
    }

    @RequestMapping("/save")
    @ResponseBody
    public Result saveOrUpdate(@RequestBody Role role){
        Result result = new Result();
        if(null != role.getId() && role.getId() != 0){
            //修改
            roleService.update(role);
        }else{
            //添加
            roleService.save(role);
        }
        result.setCode((byte) 1);
        result.setMessage("保存成功");
        return result;
    }

    /**
     * 删除
     */

    @RequestMapping(value = "/delete",method = RequestMethod.DELETE)
    @ResponseBody
    public Result delete(@RequestParam("id")Integer id){
        Result result = new Result();
        int del = roleService.delete(id);
        if(del > 0){
           result.setCode((byte) 1);
        }else{
            result.setCode((byte) 0);
            result.setMessage("删除失败");
        }
        return result;
    }
}
